package icu.yougan.trade.config;

import icu.yougan.trade.fliter.JwtAuthenticationFilter;
import icu.yougan.trade.fliter.WebSocketAuthInterceptor;
import icu.yougan.trade.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;
import org.springframework.web.socket.messaging.DefaultSimpUserRegistry;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;
import org.springframework.web.socket.messaging.SessionSubscribeEvent;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;
    // WebSocketConfig.java
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private WebSocketAuthInterceptor authInterceptor;
    // WebSocketConfig.java
    // 并在configureClientInboundChannel中注册
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(/*loggingInterceptor(),*/ authInterceptor);
    }
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        // /user前缀
        config.enableSimpleBroker("/topic", "/queue", "/user");
        config.setApplicationDestinationPrefixes("/app");
        config.setUserDestinationPrefix("/user");
    }
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws")
                .setAllowedOriginPatterns("*")
                .withSockJS();
    }
    // 新增心跳配置
    @Override
    public void configureWebSocketTransport(WebSocketTransportRegistration registration) {
        registration.setSendTimeLimit(15 * 1000) // 发送超时
                .setSendBufferSizeLimit(512 * 1024) // 缓冲区限制
                .setMessageSizeLimit(128 * 1024); // 消息大小限制
    }
//    // 添加事件监听
//    @EventListener
//    public void handleSubscribeEvent(SessionSubscribeEvent event) {
//        StompHeaderAccessor headers = StompHeaderAccessor.wrap(event.getMessage());
//        System.out.println("用户订阅: " + headers.getSessionId() +
//                " -> " + headers.getDestination());
//    }
//
//    @EventListener
//    public void handleDisconnectEvent(SessionDisconnectEvent event) {
//        System.out.println("用户断开: " + event.getSessionId());
//    }
//    @Bean
//    public ChannelInterceptor loggingInterceptor() {
//        return new ChannelInterceptor() {
//            @Override
//            public Message<?> preSend(Message<?> message, MessageChannel channel) {
//                StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
//                System.out.println("=== STOMP帧监控 ===");
//                System.out.println("命令: " + accessor.getCommand());
//                System.out.println("头信息: " + accessor.toMap());
//                if (message.getPayload() instanceof byte[]) {
//                    System.out.println("载荷: " + new String((byte[]) message.getPayload()));
//                }
//                return message;
//            }
//        };
//    }
}